"""Lead Pydantic schemas for Real Estate CRM."""

from __future__ import annotations

from datetime import datetime
from uuid import UUID

from pydantic import Field, field_validator

from ..models.enums import DemandType, LeadStage, QualityGrade, SourceChannel
from ..schemas.base import ORMBase, TimestampModel


class LeadBase(ORMBase):
    """Base Lead schema."""

    name: str = Field(..., min_length=1, max_length=100, description="客户姓名")
    phone: str = Field(..., min_length=1, max_length=20, description="手机号（唯一）")
    demand_type: DemandType = Field(..., description="需求类型")
    budget_range: str | None = Field(None, max_length=100, description="预算范围")
    source_channel: SourceChannel = Field(default=SourceChannel.OTHER, description="来源渠道")
    stage: LeadStage = Field(default=LeadStage.NEW, description="跟进阶段")
    notes: str | None = Field(None, description="备注信息（AI标签提取源）")
    tag_names: str | None = Field(
        None, max_length=500, description="标签名称（逗号分隔）：'近地铁,学区房,安静'"
    )

    @field_validator("phone")
    @classmethod
    def validate_phone(cls, v: str) -> str:
        """验证手机号格式（简单校验）."""
        import re

        if not re.match(r"^1[3-9]\d{9}$", v):
            raise ValueError("手机号格式不正确（需为11位数字，以1开头）")
        return v


class LeadCreate(LeadBase):
    """Schema for creating a lead."""

    import_batch_id: UUID | None = None  # Auto-generated if not provided
    owner_id: int


class LeadUpdate(ORMBase):
    """Schema for updating a lead."""

    name: str | None = Field(None, min_length=1, max_length=100)
    phone: str | None = Field(None, min_length=1, max_length=20)
    demand_type: DemandType | None = None
    budget_range: str | None = Field(None, max_length=100)
    source_channel: SourceChannel | None = None
    stage: LeadStage | None = None
    notes: str | None = None
    owner_id: int | None = None


class LeadOut(LeadBase, TimestampModel):
    """Schema for lead output."""

    id: int
    import_batch_id: UUID
    owner_id: int

    # Optional related data (populated by services)
    contacts_count: int = 0
    notes_count: int = 0
    ai_summaries_count: int = 0

    # MVP1: 客户质量评分字段
    quality_score: int | None = Field(None, ge=0, le=100, description="质量分数 (0-100)")
    quality_grade: QualityGrade | None = Field(None, description="质量等级 S/A/B/C/D")
    quality_updated_at: datetime | None = Field(None, description="评分更新时间")


class LeadListOut(ORMBase):
    """Schema for paginated lead list output."""

    total: int = Field(..., description="总记录数")
    items: list[LeadOut] = Field(default_factory=list, description="当前页数据")
    page: int = Field(..., ge=1, description="当前页码")
    page_size: int = Field(..., ge=1, le=200, description="每页数量")
